#include <glib.h>

/**
 * @brief test_read_line_string 读取一行数据
 * @param c     io通道
 */
static void test_read_line_string(GIOChannel *c);

static void test_read_line(GIOChannel *c);

/**
 * @brief test_read_to_end 从当前读到文件结尾
 * @param c     io通道
 */
static void test_read_to_end(GIOChannel *c);

/**
 * @brief test_line_term 测试行终止符
 * @param c     io通道
 */
static void test_line_term(GIOChannel *c);

int main(int argc,char *argv[])
{
    GError *err = NULL;
    GIOChannel *c = NULL;
//    channel = g_io_channel_new_file("http://git.oschina.net/add358/demo/raw/master/COPYING", "r", &err);
    c = g_io_channel_new_file("test.txt", "r", &err);
    if (NULL == c) {
        g_error("Error creat io channel:%s\n", err->message);
        g_error_free(err);
        return -1;
    }

//    test_line_term(c);
//    test_read_line_string(c);
//    test_read_to_end(c);
    test_read_line(c);

    return 0;
}

static void test_read_line(GIOChannel *c)
{
    gchar *str = NULL;
    gsize len = 0;
    gint i=0;

    g_io_channel_read_line(c, &str, &len, NULL, NULL);
    for (i = 0; i < len; ++i) {
        g_print("%x ", str[i]);
    }
    g_message("\n%s",str);
}

static void test_line_term(GIOChannel *c)
{
    const gchar *term = NULL;
    gint len = 0;
    gint i = 0;
    term = g_io_channel_get_line_term(c, &len);
    g_message("term=%s", term);

    g_io_channel_set_line_term(c, "\n", 1);
    term = g_io_channel_get_line_term(c, &len);
    for(i = 0; i< len; ++i) {
        g_print("%x", term[i]);
    }
    g_print("\n");

    g_io_channel_set_line_term(c, "\r", 1);
    term = g_io_channel_get_line_term(c, &len);
    for(i = 0; i< len; ++i) {
        g_print("%x", term[i]);
    }
    g_print("\n");


    g_io_channel_set_line_term(c, "\r\n", 2);
    term = g_io_channel_get_line_term(c, &len);
    for(i = 0; i< len; ++i) {
        g_print("%x ", term[i]);
    }
    g_print("\n");

    g_io_channel_set_line_term(c, "\r\n", 2);
    term = g_io_channel_get_line_term(c, &len);
    for(i = 0; i< len; ++i) {
        g_print("%x ", term[i]);
    }
    g_print("\n");
}

static void test_read_to_end(GIOChannel *c)
{
    gchar *msg = NULL;
    gsize len = 0;

    if ( g_io_channel_read_to_end(c, &msg, &len, NULL) == G_IO_STATUS_NORMAL ) {
        g_message("\n%s", msg);
    }
}

static void test_read_line_string(GIOChannel *c)
{
    GString *msg = NULL;
    GError *err = NULL;
    GIOStatus status;

    msg = g_string_sized_new(1024);

    status = g_io_channel_read_line_string(c, msg, NULL, &err);
    if (G_IO_STATUS_ERROR == status) {
        g_error("[%d]%s", err->code, err->message);
    }
    g_message("content:%s",msg->str);

    g_string_free(msg, TRUE);
}
